package game.managers
{
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.utils.Dictionary;

	/**
	 * 图片资源管理类
	 * @author xiezhicheng
	 */
	public class ResourceManager
	{
		private static var _instance:ResourceManager;
		/**图片存放字典*/
		private var _cacheDic:Dictionary;

		public function ResourceManager()
		{
			if (_instance) 
			{
				throw new Error("ResourceManager is a single class");	
			}
			_instance = this;
			_cacheDic = new Dictionary();
		}
		
		public static function getInstance():ResourceManager
		{
			if (_instance == null) 
			{
				_instance = new ResourceManager();
			}
			return _instance;
		}
		
		/**
		 * 判断字典中是否已存在该资源
		 * @param str 资源名或路径名
		 * @return 
		 */
		public function has(str:String):Boolean
		{
			return _cacheDic[str] != undefined;
		}
	
		
		/**
		 * 添加资源
		 * @param str 路径
		 * @param obj 资源
		 * @param overWrite 是否覆盖原有的图片
		 */
		public function add(str:String,obj:Object,overWrite:Boolean):void
		{
			if(_cacheDic[str] == undefined)
			{
				_cacheDic[str] = obj;
			}
			else if (overWrite) 
			{
				if (_cacheDic[str] is BitmapData) 
				{
					BitmapData(_cacheDic[str]).dispose();
				}
				_cacheDic[str] = obj ;
			}
		}
		
		
		/**
		 * 获取资源
		 * @param str
		 * @return 
		 */
		public function getResource(str:String):Object
		{
			if (_cacheDic[str] != undefined) 
			{
				return _cacheDic[str];
			}
			return null;
		}
		
		/**
		 * 移除资源
		 * @param str
		 */
		public function remove(str:String):void
		{
			if (_cacheDic[str] is BitmapData)
			{
				BitmapData(_cacheDic[str]).dispose();
			}
			delete _cacheDic[str];
		}
		
		/**
		 * 一次性清空所有资源
		 */
		public function allClear():void
		{
			for each (var key:String in _cacheDic) 
			{
				if (_cacheDic[key] is BitmapData) 
				{
					BitmapData(_cacheDic[key]).dispose();
				}
			}
			
		}
	}
}